package org.benjamin.sso.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.benjamin.sso.domain.entity.UserAuthority;
import org.benjamin.sso.domain.entity.UserInfo;
import org.benjamin.sso.repository.UserAuthorityRepository;
import org.benjamin.sso.repository.UserInfoRepository;
import org.benjamin.sso.service.UpdateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.mysql.jdbc.Driver;

@Service
public class UpdateServiceImpl implements UpdateService {
	
	private Logger logger = LogManager.getLogger();
	
	@Autowired
	private UserInfoRepository userInfoRepository;
	
	@Autowired
	private UserAuthorityRepository userAuthorityRepository;
	
	@Autowired
	private DataSource dataSource;

	@Override
	@PostConstruct
	public void initialise() {
		// xywenjie是管理员账户，自动注册
		UserInfo userInfo = this.userInfoRepository.findByUsername("xywenjie");
		if(userInfo == null) {
			userInfo = new UserInfo();
			userInfo.setUsername("xywenjie");
			String password = DigestUtils.md5Hex("huang1100");
			userInfo.setPassword(password);
			this.userInfoRepository.save(userInfo);
			
			List<UserAuthority> userAuthorities = new ArrayList<>();
			userAuthorities.add(new UserAuthority(userInfo,"ROLE_ADMIN"));
			userAuthorities.add(new UserAuthority(userInfo,"ROLE_USER"));
			this.userAuthorityRepository.save(userAuthorities);
			logger.debug("系统初始化管理员，账号：{},并拥有两个权限ROLE_USER;ROLE_ADMIN",userInfo.getUsername());
		}
	}
	
	public static DataSource getDatabaseConnection() {
		System.out.println("----获取DataSource对象----");
		BasicDataSource basicDataSource = new BasicDataSource();
		basicDataSource.setUrl("jdbc:mysql://localhost:3306/sso");
		basicDataSource.setUsername("root");
		basicDataSource.setPassword("huang1100");
		basicDataSource.setDriverClassName("com.mysql.jdbc.Driver");
		JdbcTemplate jdbcTemplate = new JdbcTemplate(basicDataSource);
		jdbcTemplate.execute("create table application_log ");
		return basicDataSource;
	}

}
